/**
 * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zntg.utils;

import org.apache.commons.lang.time.DateFormatUtils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DateUtil {


	/**
	 * 获取YYYY格式
	 *
	 * @return
	 */
	public static String getYear() {
		return formatDate(new Date(), "yyyy");
	}

	/**
	 * 获取YYYY格式
	 *
	 * @return
	 */
	public static String getYear(Date date) {
		return formatDate(date, "yyyy");
	}

	/**
	 * 获取YYYY-MM-DD格式
	 *
	 * @return
	 */
	public static String getDay() {
		return formatDate(new Date(), "yyyy-MM-dd");
	}

	/**
	 * 获取YYYY-MM-DD格式
	 *
	 * @return
	 */
	public static String getDay(Date date) {
		return formatDate(date, "yyyy-MM-dd");
	}

	/**
	 * 获取YYYYMMDD格式
	 *
	 * @return
	 */
	public static String getDays() {
		return formatDate(new Date(), "yyyyMMdd");
	}

	/**
	 * 获取YYYYMMDD格式
	 *
	 * @return
	 */
	public static String getDays(Date date) {
		return formatDate(date, "yyyyMMdd");
	}

	/**
	 * 获取YYYY-MM-DD HH:mm:ss格式
	 *
	 * @return
	 */
	public static String getTime() {
		return formatDate(new Date(), "yyyy-MM-dd HH24:mm:ss");
	}

	/**
	 * 获取YYYY-MM-DD HH:mm:ss.SSS格式
	 *
	 * @return
	 */
	public static String getMsTime() {
		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
	}

	/**
	 * 获取YYYYMMDDHHmmss格式
	 *
	 * @return
	 */
	public static String getAllTime() {
		return formatDate(new Date(), "yyyyMMddHHmmss");
	}

	/**
	 * 获取YYYY-MM-DD HH:mm:ss格式
	 *
	 * @return
	 */
	public static String getTime(Date date) {
		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
	}

	public static String formatDate(Date date, String pattern) {
		String formatDate = null;

			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");

		return formatDate;
	}

	/**
	 * @Title: compareDate
	 * @Description:(日期比较，如果s>=e 返回true 否则返回false)
	 * @param s
	 * @param e
	 * @return boolean
	 * @throws
	 * @author luguosui
	 */
	public static boolean compareDate(String s, String e) {
		if (parseDate(s) == null || parseDate(e) == null) {
			return false;
		}
		return parseDate(s).getTime() >= parseDate(e).getTime();
	}

	/**
	 * 格式化日期
	 *
	 * @return
	 */
	public static Date parseDate(String date) {
		return parse(date,"yyyy-MM-dd");
	}

	/**
	 * 格式化日期
	 *
	 * @return
	 */
	public static Date parseTime(String date) {
		return parse(date,"yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 格式化日期
	 *
	 * @return
	 */
	public static Date parse(String date, String pattern) {
		try {
			return DateUtils.parseDate(date,pattern);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 格式化日期
	 *
	 * @return
	 */
	public static String format(Date date, String pattern) {
		return DateFormatUtils.format(date, pattern);
	}

	/**
	 * 把日期转换为Timestamp
	 *
	 * @param date
	 * @return
	 */
	public static Timestamp format(Date date) {
		return new Timestamp(date.getTime());
	}

	/**
	 * 校验日期是否合法
	 *
	 * @return
	 */
	public static boolean isValidDate(String s) {
		return parse(s, "yyyy-MM-dd HH:mm:ss") != null;
	}

	/**
	 * 校验日期是否合法
	 *
	 * @return
	 */
	public static boolean isValidDate(String s, String pattern) {
        return parse(s, pattern) != null;
	}

	public static int getDiffYear(String startTime, String endTime) {
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		try {
			int years = (int) (((fmt.parse(endTime).getTime() - fmt.parse(
					startTime).getTime()) / (1000 * 60 * 60 * 24)) / 365);
			return years;
		} catch (Exception e) {
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			return 0;
		}
	}

	/**
	 * <li>功能描述：时间相减得到天数
	 *
	 * @param beginDateStr
	 * @param endDateStr
	 * @return long
	 * @author Administrator
	 */
	public static long getDaySub(String beginDateStr, String endDateStr) {
		long day = 0;
		SimpleDateFormat format = new SimpleDateFormat(
				"yyyy-MM-dd");
		Date beginDate = null;
		Date endDate = null;

		try {
			beginDate = format.parse(beginDateStr);
			endDate = format.parse(endDateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
		// System.out.println("相隔的天数="+day);

		return day;
	}

	/**
	 * 得到n天之后的日期
	 *
	 * @param days
	 * @return
	 */
	public static String getAfterDayDate(String days) {
		int daysInt = Integer.parseInt(days);

		Calendar canlendar = Calendar.getInstance(); // java.util包
		canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
		Date date = canlendar.getTime();

		SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateStr = sdfd.format(date);

		return dateStr;
	}

	/**
	 * 得到n天之后是周几
	 *
	 * @param days
	 * @return
	 */
	public static String getAfterDayWeek(String days) {
		int daysInt = Integer.parseInt(days);

		Calendar canlendar = Calendar.getInstance(); // java.util包
		canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
		Date date = canlendar.getTime();

		SimpleDateFormat sdf = new SimpleDateFormat("E");
		String dateStr = sdf.format(date);

		return dateStr;
	}
	/**
	 * 获取上月的日期
	 * @return
	 */
	public static String getBeforeMonth(){
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -1);
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM");
		String time = format.format(c.getTime());
		return time;
	}
	/**
	 * 获取本日日期
	 * @return
	 */
	public static String getToDay(){
		//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		Date todayDate=new Date();
		String today=format.format(todayDate);
		return today;
	}
	/**
	 * 获取本日日期
	 * @return
	 */
	public static String getToDayChinese(){
		//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
		Calendar c = Calendar.getInstance();
		Date todayDate=new Date();
		String today=format.format(todayDate);
		return today;
	}
	/**
	 * 获取本日日期
	 * @return
	 */
	public static String getDateNow(){
		//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSS");
		Calendar c = Calendar.getInstance();
		Date todayDate=new Date();
		String today=format.format(todayDate);
		return today;
	}
	/**
	 * 获取昨天日期
	 * @return
	 */
	public static String getYestoday(){
		Calendar   cal   =   Calendar.getInstance();
		cal.add(Calendar.DATE,   -1);
		String yesterday = new SimpleDateFormat( "yyyy-MM-dd").format(cal.getTime());
		return yesterday;
	}
	/**
	 * 获取昨天日期
	 * @return
	 */
	public static String getYestoday1(){
		Calendar   cal   =   Calendar.getInstance();
		cal.add(Calendar.DATE,   -1);
		String yesterday = new SimpleDateFormat( "yyyyMMdd").format(cal.getTime());
		return yesterday;
	}
	/**
	 * 获取本月日期
	 * @return
	 */
	public static String getMonth(){
		Calendar c = Calendar.getInstance();
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM");
		String time = format.format(c.getTime());
		System.out.println(time);
		return time;
	}
	/**
	 * 计算上月的今天
	 * @return
	 */
	public static String getBeforeMoneyToday(){
		//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		//过去一月
		c.setTime(new Date());
		c.add(Calendar.MONTH, -1);
		Date m = c.getTime();
		String mon = format.format(m);
		System.out.println("过去一个月："+mon);
		return mon;
	}

	/**
	 * 搜索离得最近的日期, 先排序再搜索, 修改下适合进行大量的快速搜索
	 * @param list
	 * @param d
	 * @return
	 */
	public static Date find1(List<Date> list, Date d){
		if(list==null || list.size()<=0){
			return null;
		}
		if(list.size()==1){
			return list.get(0);
		}
		list=new ArrayList<Date>(list);
		Collections.sort(list);

		int left=0;
		int right=list.size()-1;
		while(left<=right){
			int mid=(left+right)/2;
			int cm=d.compareTo(list.get(mid));
			if(cm<0){
				right=mid-1;
			}
			else if(cm>0){
				left=mid+1;
			}
			else{
				return list.get(mid);
			}
		}
		if(left<=0){
			return list.get(0);
		}
		if(left>=list.size()){
			return list.get(list.size()-1);
		}
		long dleft=d.getTime()-list.get(left-1).getTime();
		long dright=list.get(left).getTime()-d.getTime();
		return dleft<dright?list.get(left-1):list.get(left);
	}



	/**
	 *  @auth  zhengyunfei  2017-7-28
	 *  获取2个日期之间的日期
	 * @param start  起始日期
	 * @param end   结束日期
	 * @return
	 */
	public static List<String> getDate(String start,String end){ //
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		List<String> list = new ArrayList<String>(); //保存日期集合
		try {
			Date date_start = sdf.parse(start);
			Date date_end = sdf.parse(end);
			Date date =date_start;
			Calendar cd = Calendar.getInstance();//用Calendar 进行日期比较判断
			while (date.getTime()<=date_end.getTime()){
				list.add(sdf.format(date));
				cd.setTime(date);
				cd.add(Calendar.DATE, 1);//增加一天 放入集合
				date=cd.getTime();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 *
	 * 判断给定的日期是否是闰年
	 * @param date 2018-01-26
	 * @return
	 */
	public static boolean isRunYear(String date){
		boolean result=false;
		if(date.length()>4){
			long year = Long.parseLong(date.substring(0,4));
			//闰年需要满足的条件：能被4整除但不能被100整除，或者能被400整除，满足其中一个即可
			if((year%4==0 && year%100!=0) || year%400==0 ){
				result= true;
			}else{
				result= false;
			}
		}
		return result;
	}

	/**
	 * 格式化Oracle Date
	 * @return
	 */
//	public static String buildDateValue(Object value){
//		if(Func.isOracle()){
//			return "to_date('"+ value +"','yyyy-mm-dd HH24:MI:SS')";
//		}else{
//			return Func.toStr(value);
//		}
//	}

	/**
	 * 返回long类型的日期
	 * @return
	 */
	public static long getLongTime(){
		Date dt = new Date();
		long lSysTime1 = dt.getTime() / 1000;   //得到秒数，Date类型的getTime()返回毫秒数
		return lSysTime1;
	}

	/**
	 * 时间戳转换成日期格式字符串
	 * @param seconds 精确到秒的字符串
	 * @return
	 */
	public static String timeStamp2Date(String seconds,String format) {
		if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
			return "";
		}
		if(format == null || format.isEmpty()){
			format = "yyyy-MM-dd HH:mm:ss";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date(Long.valueOf(seconds+"000")));
	}
	/**
	 * 日期格式字符串转换成时间戳
	 * @param format 如：yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String date2TimeStamp(String date_str,String format){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return String.valueOf(sdf.parse(date_str).getTime()/1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 取得当前时间戳（精确到秒）
	 * @return
	 */
	public static String timeStamp(){
		long time = System.currentTimeMillis();
		String t = String.valueOf(time/1000);
		return t;
	}
	/**
	 * 日期格式字符串转换成时间戳（默认为上午9点，前台数据表展示用）
	 * @return
	 */
	public static String date3TimeStamp(String date_str){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return String.valueOf(sdf.parse(date_str).getTime());
		} catch (Exception e) {
            e.printStackTrace();
		}
		return "";
	}
	public static void main(String[] args) {
		System.out.println("time="+DateUtils.getCurrentDate());

	}
	/**
	* @Description:  求某天之后的多少个工作日是哪天
	* @Param: [currentDate, days]
	* @return: java.lang.String
	* @Author: zhengyunfei
	* @Date: 2018/12/10
	* @time:16:21
	*/
	public static String getWorkDay(Date currentDate,int days){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(currentDate);
		int i=0;
		while(i<days){
			calendar.add(Calendar.DATE,1);
			i++;
			if(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY ||
					calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
				i--;
			}
		}
		return sdf.format(calendar.getTime());
	}
	public static String getWorkDay(String oneDay,int days){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar=Calendar.getInstance();
		SimpleDateFormat sdfFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date currentDate= null;
		try {
			currentDate = sdfFormat.parse(oneDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		calendar.setTime(currentDate);
		int i=0;
		while(i<days){
			calendar.add(Calendar.DATE,1);
			i++;
			if(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY ||
					calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
				i--;
			}
		}
		return sdf.format(calendar.getTime());
	}
}
